package cn.xianyang.org.service.impl;

import cn.xianyang.basic.service.impl.BaseServiceImpl;
import cn.xianyang.org.domain.Department;
import cn.xianyang.org.mapper.DepartmentMapper;
import cn.xianyang.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
//只读 ,事务传播机制支持
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        String dirPath = "";
        if (department.getParent() == null){
            //新增顶级部门
            dirPath = "/"+department.getId();
        }else {
            //新增非顶级部门
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/" +department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public void batchRemove(List<Long> ids) {
        departmentMapper.batchRemove(ids);
    }

    /**
     * 无限级树实现方式
     * @return
     */
    @Override
    public List<Department> queryTree() {
        // ①一次性查询出所有数据，放到内存 all
        List<Department> departments = departmentMapper.loadAll();
        //后期为了找到自己的父亲，可以把整体的部门数据，转换成一份Map<id,department>
        //Map<Long,Department> allDepts = departments.stream().collect(Collectors.toMap(Department::getId,dept -> dept));
        HashMap<Long, Department> allDepts = new HashMap<>();
        for (Department department : departments) {
            allDepts.put(department.getId(),department);
        }
        //顶级部门
        ArrayList<Department> firstDepts = new ArrayList<>();
        for (Department tmp : departments) {
            if (tmp.getParent_id() == null){
                // ②从所有数据中找出第一层级firstCourseType  我们需要返回的数据
                firstDepts.add(tmp);
            }else {
                // ③只要不是第一层级的，找到自己的上级，并将自己放入上级的children中
                Department parent = allDepts.get(tmp.getParent_id());
                if (parent != null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDepts;
    }

}
